package net.my.msn.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import net.my.msn.domain.Message;
import net.my.msn.domain.User;
import net.my.msn.domain.Voice;
import net.my.msn.service.VoiceService;
import net.my.msn.service.MessageService;
import net.my.msn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserPageController {

	@Autowired
	UserService userService;
	@Autowired
	MessageService messageService;
	@Autowired
	VoiceService voiceService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/logout")
	public String logout() {
		return "login";

	}

	public Long idBySecurity() {
		Object obj = SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		String username = null;
		if ((obj instanceof UserDetails)
				&& (authorityBySecurity().equals("ROLE_USER")))
			username = ((UserDetails) obj).getUsername();
		User user = userService.userByName(username);
		return user.getUserId();
	}

	public String authorityBySecurity() {
		Object obj = SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		String role = null;
		Collection<GrantedAuthority> c = null;
		if (obj instanceof UserDetails) {
			c = ((UserDetails) obj).getAuthorities();
		}
		Iterator<GrantedAuthority> iter = c.iterator();
		while (iter.hasNext()) {
			role = iter.next().getAuthority();
		}
		return role;
	}

	@RequestMapping(value = "/auth")
	public String successLogin(ModelMap model) {
		String role = authorityBySecurity();
		if (role.equals("ROLE_USER"))
			return "redirect:user" + idBySecurity();
		else
			return "redirect:users";
	}

	@RequestMapping(value = "/user{user_id}", method = RequestMethod.GET)
	public ModelAndView showUserPage(@PathVariable("user_id") Long userId) {
		boolean isAdmin = false;
		ModelMap modelMap = new ModelMap();
		User user = userService.userOut(userId);
		List<Message> mes = user.getMessages();
		List<Integer> voices = new ArrayList<Integer>();
		List<String> senderLastname = new ArrayList<String>();
		List<String> senderFirstname = new ArrayList<String>();
		for (Message m : mes) {
			voices.add(voiceService.findVoiceByMessageId(m.getMessageId()));
			senderLastname.add(userService.findBySender(m.getSenderId())
					.getLastname());
			senderFirstname.add(userService.findBySender(m.getSenderId())
					.getFirstname());
		}
		if (authorityBySecurity().equals("ROLE_ADMIN"))
			isAdmin = true;
		if (authorityBySecurity().equals("ROLE_USER"))
			modelMap.addAttribute("default_user_id", idBySecurity());
		modelMap.addAttribute("isAdmin", isAdmin);
		modelMap.addAttribute("user_id", userId);
		modelMap.addAttribute("sender_lastname", senderLastname);
		modelMap.addAttribute("sender_firstname", senderFirstname);
		modelMap.addAttribute("voices", voices);
		modelMap.addAttribute("about_user", userService.userOut(userId));
		return new ModelAndView("userpage", modelMap);

	}

	@RequestMapping(value = "user{user_id}", method = RequestMethod.POST)
	public String onSubmit(@PathVariable("user_id") Long userId,
			@RequestParam("messageContent") String messageContent) {

		if (messageContent.trim().equals(""))
			return "redirect:user" + userId;
		else {
			messageService.addMessage(messageContent, userId, idBySecurity());
			return "redirect:user" + userId;
		}

	}

	@RequestMapping(value = "add_voice_{user_id}_{u.messageId}")
	public String addVoice(@PathVariable("user_id") Long userId,
			@PathVariable("u.messageId") Long messageId) {
		voiceService.addVoice(new Voice(), messageId, idBySecurity());
		return "redirect:user" + userId;

	}

	@RequestMapping(value = "delete_message_{user_id}_{u.messageId}")
	public String deleteMessage(@PathVariable("user_id") Long userId,
			@PathVariable("u.messageId") Long messageId) {
		messageService.deleteMessage(messageId);
		return "redirect:user" + userId;

	}

}
